package com.bf.electroplating.util.easyexcel.utils;

import com.bf.electroplating.pojo.vo.ResultVO;
import com.bf.electroplating.pojo.vo.attachment.AttachmentVo;
import com.bf.electroplating.service.PubAttachmentService;
import com.bf.electroplating.util.MultipartFileUtils;
import com.bf.electroplating.util.easyexcel.excel.problem.ProblemFindingExcel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@Slf4j
@Component
public class ProblemImageUtils {

    @Resource
    private PubAttachmentService pubAttachmentService;

    /**
     * 图片处理
     */
    public Map<String, List<String>> imageProcess(MultipartFile file) {
        if (file == null) {
            log.warn("文件为空，无法处理图片");
            return null;
        }
        Map<String, List<String>> images = new HashMap<>();
        try {
            ZipSecureFile.setMinInflateRatio(-1.0d);
            OPCPackage opcPackage = OPCPackage.open(file.getInputStream());
            XSSFWorkbook book = new XSSFWorkbook(opcPackage);
            XSSFSheet xssSheet = book.getSheetAt(0);
            // 获取工作表中绘图包
            XSSFDrawing drawing = xssSheet.getDrawingPatriarch();
            // 获取所有图像形状
            List<XSSFShape> shapes = drawing.getShapes();
            // 遍历所有形状
            for (XSSFShape shape : shapes) {
                ProblemFindingExcel problemFindingExcel = new ProblemFindingExcel();
                // 获取形状在工作表中的顶点位置信息（anchor锚点）
                XSSFClientAnchor anchor = (XSSFClientAnchor) shape.getAnchor();
                // 图片形状在工作表中的位置, 所在行列起点和终点位置
                short c1 = anchor.getCol1();
                String r1 = String.valueOf(anchor.getRow1());
                String key = r1 + "行," + c1 + "列";
                if (shape instanceof XSSFPicture) {
                    try {
                        XSSFPicture pic = (XSSFPicture) shape;
                        // 形状获取对应的图片数据
                        XSSFPictureData picData = pic.getPictureData();
                        // 保存图片到本地
                        byte[] data = picData.getData();
                        String fileName = "image_" + UUID.randomUUID() + "." + picData.suggestFileExtension();
                        String contentType = picData.suggestFileExtension().equals("jpg") ? "image/jpeg" : "image/png"; // 根据文件扩展名确定内容类型
                        MultipartFile multipartFile = MultipartFileUtils.convert(data, fileName, contentType);
                        ResultVO<AttachmentVo> attachmentVoResultVO = pubAttachmentService.uploadFile(multipartFile);
                        // TODO 放入excel集合，这里行数要减去1，获取图片是从表头开始（表头位置为0），获取excelVos是从数据开始（第一条数据位置为0）他们相差一个表头，所以要减去1才能对应
                        if (images.get(r1) == null) {
                            List<String> list = new ArrayList<>();
                            list.add(attachmentVoResultVO.getData().getId());
                            images.put(r1, list);
                        } else {
                            List<String> list = images.get(r1);
                            list.add(attachmentVoResultVO.getData().getId());
                        }
                    } catch (Exception e) {
                        log.error("asyncImportList XSSFClientAnchor key|{} error|{}", key, e.getMessage());
                    }
                } else {
                    problemFindingExcel.setImages(null);
                }
            }

        } catch (Exception e) {
            log.error("asyncImportList XSSFWorkbook error|{}", e.getMessage());
        }
        return images;
    }

}
